<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @reset="handleReset" @submit="handleSubmit">
      <template #chanSelect="{ model, field }">
        <n-select v-model:value="model[field]" :options="registChanArray" />
      </template>
    </BasicForm>

    <BasicTable
      ref="actionRef"
      :actionColumn="actionColumn"
      :columns="columns"
      :initRequest="false"
      :loading="loading"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      :scroll-x="1090"
      @update:checked-row-keys="onCheckedRow"
    >
      <template #tableTitle>
        <n-button type="primary" @click="handlerAddChan">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          添加渠道
        </n-button>
      </template>

      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>
  </n-card>
  <basicModal
    ref="modalRef"
    class="basicModal"
    style="width: 30%"
    @register="modalRegister"
    @on-ok="okModal"
  >
    <template #default>
      <BasicForm class="basicForm" @register="addRegister">
        <template #chanLevelSelect="{ model, field }">
          <n-select v-model:value="model[field]" :options="chanlLevelOptions" clearable />
        </template>
        <template #gameSelect="{ model, field }">
          <n-select v-model:value="model[field]" :options="gameOptions" clearable />
        </template>
      </BasicForm>
    </template>
  </basicModal>

  <basicModal
    ref="modalRef"
    class="basicModal"
    style="width: 30%"
    @register="modalBindRegister"
    @on-ok="clickBindSubmit"
  >
    <BasicForm class="basicForm" @register="bindRegister">
      <template #gameSelect="{ model, field }">
        <n-select v-model:value="model[field]" :options="gameOptions" clearable />
      </template>
    </BasicForm>
  </basicModal>

  <basicModal
    ref="modalRef"
    class="basicModal"
    style="width: 30%"
    @register="modalBindAnchor"
    @on-ok="clickBindAnchorSubmit"
  >
    <BasicForm class="basicForm" @register="bindAnchor">
      <template #anchorSelect="{ model, field }">
        <n-select v-model:value="model[field]" :options="anchorOptions" clearable />
      </template>
      <template #gameSelect="{ model, field }">
        <n-select v-model:value="model[field]" :options="gameOptions" clearable />
      </template>
    </BasicForm>
  </basicModal>

  <basicModal
    ref="modalRef"
    class="basicModal"
    style="width: 30%"
    @register="modalBindDownload"
    @on-ok="clickBindDownloadSubmit"
  >
    <BasicForm class="basicForm" @register="bindDownload" />
  </basicModal>
</template>

<script lang="ts" setup>
  import { h, onMounted, reactive, ref, unref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import {
    addCloumns,
    bindAnchorCloumns,
    bindCloumns,
    bindDownloadCloumns,
    columns,
  } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { useModal } from '@/components/Modal';
  import { getGameAll } from '@/api/game/game';
  import { GameAnchorBindChan, getGameAnchorInfo, getGameAnchorList } from '@/api/game/gameAnchor';
  import { getChanFilter, getChanList, registerChan, updateChanManage } from '@/api/game/chan';

  const registChanArray = ref([]);
  const gameOptions = ref([]);
  const anchorOptions = ref([]);
  const chanlLevelOptions = [
    { label: '一级渠道', value: 'First' },
    { label: '二级渠道', value: 'Second' },
    { label: '三级渠道', value: 'Thrid' },
    { label: '四级渠道', value: 'Forth' },
  ];

  const schemas: FormSchema[] = [
    {
      field: 'chanName',
      labelMessage: '渠道昵称',
      component: 'NInput',
      label: '渠道昵称',
      componentProps: {
        placeholder: '渠道昵称',
      },
    },
    {
      field: 'chanId',
      labelMessage: '渠道标识',
      component: 'NInput',
      label: '渠道标识',
      componentProps: {
        placeholder: '渠道标识',
      },
    },
  ];

  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();
  const tableDataSource = ref([]);
  const showModal = ref(false);
  let loading = ref(false);
  const formBtnLoading = ref(false);
  const bindBtnLoading = ref(false);
  const isEdit = ref(false);
  const formParams = reactive({
    pageSize: 10,
    page: 0,
    chanName: '',
    chanId: '',
    anchorId: 0,
  });
  const updateChan = ref({});

  const params = ref({
    chanDesc: '',
    chanId: '',
    chanLevel: '',
    chanName: '',
    chanStatus: '',
    createTime: '',
    gameId: '',
    anchorId: 0,
    gameName: '',
    hasReflectbtn: '',
    id: 0,
    updateTime: '',
  });

  const bindDownloadParams = ref({
    url: '',
    cmd: '',
  });

  const anchorBindChanParams = ref({
    chanId: '',
    anchorId: '',
    refferId: '',
  });

  const actionColumn = reactive({
    width: 400,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '渠道绑定游戏',
            onClick: handleBindGame.bind(null, record),
            type: 'warning',
            ifShow: () => {
              return true;
            },
          },
          {
            label: '主播绑定',
            onClick: handleBindAnchor.bind(null, record),
            type: 'success',
            ifShow: () => {
              return true;
            },
          },
          {
            label: '落地页',
            onClick: handleBindDownload.bind(null, record),
            type: 'error',
            ifShow: () => {
              return true;
            },
          },
          {
            label: '编辑',
            onClick: handleEditChan.bind(null, record),
            type: 'info',
            ifShow: () => {
              return true;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 120,
    schemas,
  });

  //打开添加渠道面板
  async function handlerAddChan() {
    isEdit.value = false;
    await openModal();
    setProps({ title: '添加' });
    updateChan.value = {};
  }

  const [modalRegister, { openModal, closeModal, setSubLoading, setProps }] = useModal({
    title: '编辑',
  });

  const [
    modalBindRegister,
    { openModal: bindOpenModal, closeModal: bindCloseModal, setSubLoading: bindSetSubLoading },
  ] = useModal({
    title: '绑定游戏',
  });

  const [
    modalBindAnchor,
    {
      openModal: bindOpenAnchorModal,
      closeModal: bindCloseAnchorModal,
      setSubLoading: bindAnchorSetSubLoading,
    },
  ] = useModal({
    title: '绑定主播',
  });

  const [
    modalBindDownload,
    {
      openModal: bindOpenDownloadModal,
      closeModal: bindCloseDownloadModal,
      setSubLoading: bindDownloadSetSubLoading,
    },
  ] = useModal({
    title: '生成落地页',
  });

  const [addRegister, { submit: addSubmit, setFieldsValue: addSetFieldsValue }] = useForm({
    gridProps: { cols: 1 },
    collapsedRows: 3,
    labelWidth: 120,
    layout: 'horizontal',
    submitButtonText: '提交保存',
    showActionButtonGroup: false,
    schemas: addCloumns,
  });

  async function clickBindSubmit() {
    let formParam;
    try {
      formParam = await bindSubmit();
    } catch (e) {
      bindSetSubLoading(false);
    }
    let params = Object.assign({}, unref(updateChan), unref(formParam));
    try {
      await updateChanManage(params);
      message.success('关联游戏成功');
      bindCloseModal();
      await reloadTable();
    } finally {
      bindSetSubLoading(false);
    }
  }

  const [bindRegister, { submit: bindSubmit, setFieldsValue: bindSetFieldsValue }] = useForm({
    gridProps: { cols: 1 },
    collapsedRows: 3,
    labelWidth: 120,
    layout: 'horizontal',
    submitButtonText: '提交保存',
    showActionButtonGroup: false,
    schemas: bindCloumns,
  });

  async function clickBindAnchorSubmit() {
    let formParam;
    try {
      formParam = await bindAnchorSubmit();
    } catch (e) {
      bindAnchorSetSubLoading(false);
    }
    console.log('updateChan');
    console.log(updateChan);
    console.log('formParam');
    console.log(formParam);
    let params = Object.assign({}, unref(updateChan), unref(formParam));

    try {
      console.log('bindAnchorSubmit_params');
      console.log(params);
      await GameAnchorBindChan({
        anchorId: params.anchorId,
        referId: params.id,
        chanId: params.chanId,
      });
      message.success('关联主播成功');
      bindCloseAnchorModal();
      await reloadTable();
    } finally {
      bindAnchorSetSubLoading(false);
    }
  }

  const [bindAnchor, { submit: bindAnchorSubmit, setFieldsValue: bindAnchorSetFieldsValue }] =
    useForm({
      gridProps: { cols: 1 },
      collapsedRows: 3,
      labelWidth: 120,
      layout: 'horizontal',
      submitButtonText: '提交保存',
      showActionButtonGroup: false,
      schemas: bindAnchorCloumns,
    });

  const [bindDownload, { submit: bindDownloadSubmit, setFieldsValue: bindDownloadSetFieldsValue }] =
    useForm({
      gridProps: { cols: 1 },
      collapsedRows: 3,
      labelWidth: 120,
      layout: 'horizontal',
      submitButtonText: '提交保存',
      showActionButtonGroup: false,
      schemas: bindDownloadCloumns,
    });

  async function handleBindGame(record: Recordable) {
    await bindOpenModal();
    updateChan.value = unref(record);
    let param = Object.assign(
      {},
      {
        chanName: unref(record).chanName,
        gameId: unref(record).gameId,
      }
    );
    console.log(param);
    bindSetFieldsValue(param);
  }

  async function handleBindAnchor(record: Recordable) {
    await bindOpenAnchorModal();

    const anchorInfo = await getGameAnchorInfo({
      chanId: unref(record).chanId,
      referId: unref(record).id,
    });
    console.log('anchorInfo');
    console.log(anchorInfo);
    updateChan.value = unref(record);
    if (anchorInfo != null) {
      let param = Object.assign(
        {},
        {
          anchorId: anchorInfo.parentId,
        }
      );
      console.log(param);
      bindAnchorSetFieldsValue(param);
    }
  }

  async function handleBindDownload(record: Recordable) {
    await bindOpenDownloadModal();
    updateChan.value = unref(record);
    console.log('record');
    console.log(record);
    const downloadObj = eval('(' + record.chanDesc + ')');
    if (record.chanDesc != null) {
      let param = Object.assign({}, downloadObj);
      console.log(param);
      bindDownloadSetFieldsValue(param);
    }
  }

  async function clickBindDownloadSubmit() {
    let bindDownloadParams;
    try {
      bindDownloadParams = await bindDownloadSubmit();
    } catch (e) {
      bindSetSubLoading(false);
    }

    let params = Object.assign({}, unref(updateChan));

    params.chanDesc = JSON.stringify(bindDownloadParams);
    console.log('clickBindDownloadSubmit params');
    console.log(params);
    try {
      await updateChanManage(params);
      message.success('生成落地页成功');
      bindCloseDownloadModal();
      await reloadTable();
    } finally {
      bindDownloadSetSubLoading(false);
    }
  }

  async function okModal() {
    let formValue;
    try {
      formValue = await addSubmit();
    } catch (e) {
      message.error('请填写完整信息');
    } finally {
      setSubLoading(false);
    }
    unref(formValue).hasReflectbtn = unref(formValue).hasReflectbtn ? 'able' : 'disable';
    unref(formValue).chanStatus = unref(formValue).chanStatus ? 'able' : 'disable';
    unref(formValue).rankStatus = unref(formValue).rankStatus ? 'able' : 'disable';
    let value = Object.assign({}, unref(params), unref(updateChan), unref(formValue));
    try {
      if (isEdit.value) {
        await updateChanManage(value);
        message.success('编辑成功');
      } else {
        await registerChan(value);
        message.success('添加成功');
      }
      closeModal();
    } finally {
      setSubLoading(false);
    }

    await reloadTable();
  }

  const searchTable = async (param) => {
    return await getChanFilter(unref(param));
  };

  const loadDataTable = async (res) => {
    console.log('res', res);
    const param = { ...formParams, ...res };
    if (param.chanName && param.chanName != '') {
      console.log(param);
      return await getChanFilter(param);
      //tableDataSource.value = data ? data : []
    } else {
      let data = await getChanList(param);
      console.log(data);
      data.total = data.rows;
      return data;
      //tableDataSource.value = data ? data : []
    }
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  async function reloadTable() {
    actionRef.value.reload();
  }

  async function handleEditChan(record: Recordable) {
    isEdit.value = true;
    await openModal();
    setProps({ title: '编辑' });
    updateChan.value = record;
    let param = Object.assign({}, unref(record), {
      hasReflectbtn: unref(record).hasReflectbtn == 'able',
      chanStatus: unref(record).chanStatus == 'able',
      rankStatus: unref(record).rankStatus == 'able',
    });
    console.log(param);
    addSetFieldsValue(param);
  }

  async function handleSubmit(values: Recordable) {
    console.log(values);
    Object.assign(unref(formParams), values);
    formParams.page = 0;
    console.log('filter', formParams);
    reloadTable();
  }

  function handleReset(values: Recordable) {
    reloadTable();
  }

  onMounted(async () => {
    let gameVal = await getGameAll();
    gameOptions.value = gameVal.map((value) => {
      return {
        label: value.gameName,
        value: value.gameId,
      };
    });
    let anchorVal = await getGameAnchorList({ parentId: 0, pageSize: 1000 });
    anchorOptions.value = anchorVal.list.map((value) => {
      return {
        label: value.name,
        value: value.id,
      };
    });
    reloadTable();
  });
</script>

<style lang="less" scoped></style>
